using Dapper;
using Finance.Api.Read.Applications.Commands.调拨出入库记录;
using Finance.Api.Read.Dtos;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;

namespace Finance.Api.Read.Applications.CommandHands.调拨出入库记录
{
    public class DeployGoinRecordQueryCommandHandlers : IRequestHandler<DeployGoinRecordQueryCommand, ApiResult<List<DeployGoinRecordDto>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<DeployGoinRecordQueryCommandHandlers> _logger;

        public DeployGoinRecordQueryCommandHandlers(IDapperDb db, ILogger<DeployGoinRecordQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<List<DeployGoinRecordDto>>> Handle(DeployGoinRecordQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<DeployGoinRecordDto>>();

            try
            {
                var sql = @"
                    SELECT 
                        dg.GoinNo,
                        dg.GoinTime,
                        dg.GoinBox,
                        GROUP_CONCAT(dgd.ProductName SEPARATOR ',') as ProductNames,
                        SUM(dgd.OutNumNow) as TotalGoinNum,
                        dg.Goinmessage
                    FROM DeployGoin dg
                    LEFT JOIN DeployGoinDetail dgd ON dg.Id = dgd.GoinId
                    WHERE dg.Deployment = @Deployment AND dg.IsDelete = 0
                    GROUP BY dg.Id, dg.GoinNo, dg.GoinTime, dg.GoinBox, dg.Goinmessage
                    ORDER BY dg.GoinTime DESC";

                var parameters = new DynamicParameters();
                parameters.Add("@Deployment", request.Deployment);

                var list = await _db.Query<DeployGoinRecordDto>(sql, parameters);

                result.data = list.ToList();
                result.message = "调拨入库记录查询成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("调拨入库记录查询失败: {Message}", ex.Message);
                result.message = "调拨入库记录查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 